package com.wangzhenyu.common.util.storage

import android.content.ContentValues
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import androidx.activity.result.ActivityResultLauncher
import com.wangzhenyu.common.util.log.LogUtil
import com.wangzhenyu.common.util.permission.PermissionUtil
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStream

object StorageUtil {


    interface IFile {


    }

    open class BaseRequest {

        //Android 11相对路径
        var file: File? = null

        //type文件类型
        var type: String? = null

    }

    class FileRequest : BaseRequest() {




    }


    //保存图片到共享存储空间
    fun savePicture(
        context: Context,
        pictureName: String,
        bitmap: Bitmap
    ): Boolean {

        //文件名和路径
        val fileAbsolutePath =
            Environment.getExternalStorageDirectory().absolutePath + File.separator + Environment.DIRECTORY_PICTURES + File.separator + "WZYPictures"
        val openOutputStream: OutputStream?
        val uri: Uri?

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Environment.isExternalStorageLegacy()) {
            //开启了分区存储
            val contentValues = ContentValues()
            contentValues.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, pictureName)
            contentValues.put(
                MediaStore.Images.ImageColumns.RELATIVE_PATH,
                Environment.DIRECTORY_PICTURES + "/WZYPictures"
            )
            LogUtil.default01(Environment.DIRECTORY_PICTURES + "/WZYPictures")
            //开始插入
            uri = context.contentResolver.insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                contentValues
            ) ?: return false
            openOutputStream = context.contentResolver.openOutputStream(uri)
        } else {
            //未开启分区存储，使用传统方式
            File(fileAbsolutePath).apply {
                if (!exists()) mkdirs()
            }
            openOutputStream = FileOutputStream(fileAbsolutePath + File.separator + pictureName)
        }


        return try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, openOutputStream)
        } catch (e: Exception) {
            LogUtil.default01(e.message.toString())
            false
        } finally {
            openOutputStream?.close()
        }

    }


}